//-----------------------------------------------------------------------
// <copyright file="LabelGet.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Andy Reeves</author>
// <email>andyr</email>
// <date>2004-03-23</date>
// <summary>Increments the version number, labels Visual SourceSafe and does a get against the new label.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Sdc.Tasks.SourceSafe
{
    using System;
    using System.Xml;
    using System.Globalization;
    using System.IO;
    using Microsoft.Win32;
    using Microsoft.Sdc.Tasks.Configuration;
    using Microsoft.Build.Framework;

    /// <summary>
    /// Increments the version number, labels Visual SourceSafe and does a get against the new label.
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[
    /// <SourceSafe.LabelGet
    ///             Database="database"
    ///             Username="username" 
    ///             Password="password" 
    ///             GetParameter="getParameter" 
    ///             Label="label" 
    ///             OnlyIncremementRevision="onlyIncrementRevision" 
    ///             Project="project"
    ///             VersionNumber="versionNumber"
    ///             VersionNumberConfigFileLocation="versionNumberConfigFileLocation"
    ///             VersionNumberConfigVSSLocation="versionNumberConfigVSSLocation"
    ///             WorkingDirectory="workingDirectory" >
    /// </SourceSafe.LabelGet>
    /// ]]></code>
    /// <para>where:</para>
    /// <para><i>database</i></para>
    /// <para>The VSS database location. This database must exist and must be a valid VSS database.</para>
    /// <para><i>username</i></para>
    /// <para>The username that will be used when labelling VSS</para>
    /// <para><i>password</i></para>
    /// <para>The password for the username specified in <i>username</i></para>
    /// <para><i>getParameter</i></para>
    /// <para>Allows a specific version of files/projects to be supplied</para>
    /// <para><i>label</i></para>
    /// <para>Label to use when getting a particular version.</para>
    /// <para><i>onlyIncremementRevision</i></para>
    /// <para>Force Revision only change. So 2.0.1188.14 would be 2.0.1188.15 on the next automatic label from the source control system.</para>
    /// <para><i>project</i></para>
    /// <para>The VSS style syntax for project location.</para>
    /// <para><i>versionNumber</i></para>
    /// <para>If specified then $(VersionNumber) is set to this value and replaced as appropriate in the xml config file</para>
    /// <para><i>versionNumberConfigFileLocation</i></para>
    /// <para>Fully Qualified file name to the xml config file. The file contains, in Xml format, the major, minor, build and revision number.</para>
    ///
    /// For example:
    /// 
    /// <example>
    /// <code><![CDATA[
    /// <?xml version="1.0" encoding="utf-8"?>
    ///     <configuration>
    ///         <appSettings>
    ///             <add key="major" value="1" />
    ///             <add key="minor" value="2" />
    ///             <add key="build" value="1354" />
    ///             <add key="revision" value="155" />
    ///         </appSettings>
    ///     </configuration>
    /// ]]></code>    
    /// </example>
    ///
    /// <para><i>versionNumberConfigVSSLocation</i></para>
    /// <para>The path to the config file specified in <i>versionNumberConfigFileLocation</i> inside VSS, using VSS-style notation.</para>
    /// <para><i>workingDirectory</i></para>
    /// <para>The full path to the working directory on the local machine for the cod</para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <SourceSafe.LabelGet
    ///               Database='\\build5\SourceSafe\Pilot\db'
    ///               Project='$/Projects/Main/$(VersionName)'
    ///               Username='myDomain\theBuilder' 
    ///               Password='123$abc' />
    ///         </SourceSafe.LabelGet> 
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class LabelGet : TaskBase
    {

        private string project;
        private string database;
        private string username;
        private string password;
        private string label;
        private string getParameter;
        private string workingDirectory;
        private string buildNumberFull;
        private string versionNumberConfigFileLocation;
        private string versionNumberConfigVSSLocation;
        private DateTime startDate;
        private int buildBuildNumber;
        private bool onlyIncrementRevision;
        private int revisionBuildNumber;
        private int majorBuildNumber;
        private int minorBuildNumber;
        private XmlDocument versionConfig = new XmlDocument();

        /// <summary>
        /// Initializes a new instance of the LabelGetFromSourceSafe class.
        /// </summary>
        public LabelGet()
        {
        }

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            #region Execute code

            RegistryKey vssKey = null;
            string pathToSourceSafe = "";

            vssKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\6.0\Setup\Microsoft Visual SourceSafe Server");
            if (vssKey == null)
            {
                //couldn't find the Server key so try the other one
                vssKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\6.0\Setup\Microsoft Visual SourceSafe");
            }

            ShellExecute shellExecute = new ShellExecute();
            if (vssKey != null)
            {
                pathToSourceSafe = Convert.ToString(vssKey.GetValue("ProductDir"), CultureInfo.InvariantCulture);
                shellExecute.Filename = Path.Combine(pathToSourceSafe, @"win32\ss.exe");
                vssKey.Close();
            }
            else
            {
                shellExecute.Filename = "ss.exe";
            }

            shellExecute.EnvironmentVariables["SSDIR"] = this.Database;
            if (string.IsNullOrEmpty(this.Username))
            {
                this.Username = Environment.UserName;
            }

            shellExecute.EnvironmentVariables["SSUSER"] = this.Username;
            if (string.IsNullOrEmpty(this.Password) == false)
            {
                shellExecute.EnvironmentVariables["SSPWD"] = this.Password;
            }

            /*
                                check out versionNumberConfigVSSLocation file
                                load the file
                                read build, revision and startDate
                                calculate new build no.
                                if (new build> buildno) {
                                    buildno = newbuild
                                    revision = 0
                                    } else {
                                    revision++
                                    }
                                    save file
                                    check it in
                                    Set buildnumber field
                                    Label the parent to the working directory with build number
                                    Get on this label
                                    */

            FileInfo fi = new FileInfo(this.versionNumberConfigFileLocation);
            fi.Attributes = FileAttributes.Normal;
            //fi.Delete();

            string args = String.Format(CultureInfo.InvariantCulture, "Checkout -GL{2} -I-N -O@{0}\\VSSCheckout.txt {1}",
                Path.Combine(Environment.CurrentDirectory, "Output"),
                versionNumberConfigVSSLocation,
                fi.DirectoryName);

            Log.LogMessageFromResources("Vss.Connect");
            Log.LogMessageFromResources("Vss.CheckOut", this.versionNumberConfigVSSLocation);

            shellExecute.Arguments = args;

            //Log.LogMessage(shellExecute.Filename + " " + shellExecute.Arguments);
            shellExecute.Execute();
            Log.LogMessage(shellExecute.StandardError);

            this.IncrementVersionNumbers();

            args = String.Format(CultureInfo.InvariantCulture, "Checkin -GL{2} -I-N -O@{0}\\VSSCheckin.txt {1}",
                Path.Combine(Environment.CurrentDirectory, "Output"),
                versionNumberConfigVSSLocation,
                fi.DirectoryName);

            Log.LogMessageFromResources("Vss.Connect");
            Log.LogMessageFromResources("Vss.CheckIn", this.versionNumberConfigVSSLocation);

            shellExecute.Arguments = args;
            shellExecute.Execute();
            Log.LogMessage(shellExecute.StandardError);

            args = String.Format(CultureInfo.InvariantCulture, "Label -I-Y -O@{0}\\VSSLabel.txt -L{1} {2}",
                Path.Combine(Environment.CurrentDirectory, "Output"),
                buildNumberFull,
                project);

            shellExecute.Arguments = args;
            shellExecute.Execute();
            Log.LogMessage(shellExecute.StandardError);

            this.VSSGet(shellExecute, project, buildNumberFull, getParameter, workingDirectory);

            #endregion
        }


        private void IncrementVersionNumbers()
        {
            this.LoadVersionNumber();
            int newBuild = (DateTime.Now - this.startDate).Days;
            if ((newBuild > this.buildBuildNumber) && !this.onlyIncrementRevision)
            {
                this.buildBuildNumber = newBuild;
                this.revisionBuildNumber = 0;
            }
            else
            {
                revisionBuildNumber++;
            }
            SaveVersionNumber();
        }

        private void LoadVersionNumber()
        {
            this.versionConfig.Load(this.versionNumberConfigFileLocation);

            XmlNode majorNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='major']");
            if (majorNode != null)
            {
                this.majorBuildNumber = XmlConvert.ToInt32(majorNode.Attributes["value"].Value);
            }

            XmlNode minorNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='minor']");
            if (minorNode != null)
            {
                this.minorBuildNumber = XmlConvert.ToInt32(minorNode.Attributes["value"].Value);
            }

            XmlNode buildNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='build']");
            if (buildNode != null)
            {
                this.buildBuildNumber = XmlConvert.ToInt32(buildNode.Attributes["value"].Value);
            }

            XmlNode revisionNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='revision']");
            if (revisionNode != null)
            {
                this.revisionBuildNumber = XmlConvert.ToInt32(revisionNode.Attributes["value"].Value);
            }

            XmlNode startDateNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='startDate']");
            if (startDateNode != null)
            {
                this.startDate = XmlConvert.ToDateTime(startDateNode.Attributes["value"].Value, "yyyy-MM-dd");
            }

            buildNumberFull = String.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", majorBuildNumber, minorBuildNumber, buildBuildNumber, this.revisionBuildNumber);
        }

        private void SaveVersionNumber()
        {
            XmlNode majorNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='major']");
            XmlNode minorNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='minor']");
            XmlNode buildNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='build']");
            XmlNode revisionNode = this.versionConfig.SelectSingleNode("configuration/appSettings/add[@key='revision']");

            majorNode.Attributes["value"].InnerText = XmlConvert.ToString(this.majorBuildNumber);
            minorNode.Attributes["value"].InnerText = XmlConvert.ToString(this.minorBuildNumber);
            buildNode.Attributes["value"].InnerText = XmlConvert.ToString(this.buildBuildNumber);
            revisionNode.Attributes["value"].InnerText = XmlConvert.ToString(this.revisionBuildNumber);

            this.buildNumberFull = String.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", majorBuildNumber, minorBuildNumber, buildBuildNumber, this.revisionBuildNumber);
            this.versionConfig.Save(this.versionNumberConfigFileLocation);
        }

        private void VSSGet(ShellExecute shellExecute, string project, string label, string getParameter, string workingDirectory)
        {
            if (label.Length == 0)
            {
                if (getParameter != null && getParameter.Length != 0)
                {
                    label = "-VL" + getParameter;
                }
            }
            else
            {
                label = "-VL" + label;
            }

            Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "Output"));
            string getLocation = null;
            if (workingDirectory != null && workingDirectory.Length > 0)
            {
                getLocation = workingDirectory;
            }
            else
            {
                getLocation = Path.Combine(Environment.CurrentDirectory, "..");
            }
            string args = String.Format(CultureInfo.InvariantCulture," Get -GL{0} -I-N -R -O@{1}\\VSSGet.txt {2} {3}",
                getLocation,
                Path.Combine(Environment.CurrentDirectory, ".\\Output"),
                label,
                project);

            Log.LogMessageFromResources("Vss.Connect");
            if (label.Length == 0)
            {
                Log.LogMessageFromResources("Vss.GetLatest");
            }
            else
            {
                Log.LogMessageFromResources("Vss.Get", label.Substring(3));
            }

            shellExecute.Arguments = args;
            shellExecute.Execute();
            Log.LogMessage(MessageImportance.Low, shellExecute.StandardError);
        }

        public string Project
        {
            get
            {
                return (project == null ? String.Empty : project);
            }
            set
            {
                project = value;
            }
        }

        public string Database
        {
            get
            {
                return (database == null ? String.Empty : database);
            }
            set
            {
                database = value;
            }
        }

        public string Username
        {
            get
            {
                return (username == null ? String.Empty : username);
            }
            set
            {
                username = value;
            }
        }

        public string Password
        {
            get
            {
                return (password == null ? String.Empty : password);
            }
            set
            {
                password = value;
            }
        }

        public string Label
        {
            get
            {
                return (label == null ? String.Empty : label);
            }
            set
            {
                label = value;
            }
        }

        public string GetParameter
        {
            get
            {
                return (getParameter == null ? String.Empty : getParameter);
            }
            set
            {
                getParameter = value;
            }
        }

        public string WorkingDirectory
        {
            get
            {
                return (workingDirectory == null ? String.Empty : workingDirectory);
            }
            set
            {
                workingDirectory = value;
            }
        }

        public string VersionNumber
        {
            get
            {
                return (buildNumberFull == null ? String.Empty : buildNumberFull);
            }
            set
            {
                buildNumberFull = value;
            }
        }

        public string VersionNumberConfigFileLocation
        {
            get
            {
                return (versionNumberConfigFileLocation == null ? String.Empty : versionNumberConfigFileLocation);
            }
            set
            {
                versionNumberConfigFileLocation = value;
            }
        }



        public string VersionNumberConfigVSSLocation
        {
            get
            {
                return (versionNumberConfigVSSLocation == null ? String.Empty : versionNumberConfigVSSLocation);
            }
            set
            {
                versionNumberConfigVSSLocation = value;
            }
        }

        public bool OnlyIncrementRevision
        {
            get
            {
                return onlyIncrementRevision;
            }
            set
            {
                onlyIncrementRevision = value;
            }
        }
    }
}


